<?php


namespace App\Http\Controllers\Product;


use App\Http\Controllers\Controller;
use App\Http\Requests\Product\book\StoreRequest;
use App\Http\Searchs\Product\BookSearch;
use App\Repositories\ProductBook;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class BookController extends Controller
{
    /**
     * @var ProductBook
     * @author luffyzhao@vip.126.com
     */
    private $book;

    /**
     * BookController constructor.
     * @param ProductBook $book
     * @author luffyzhao@vip.126.com
     */
    public function __construct(ProductBook $book)
    {
        $this->book = $book;
    }

    /**
     * @param BookSearch $search
     * @return JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function index(BookSearch $search)
    {
        return $this->response(
            $this->book->paginate($search->toArray())
        );
    }

    /**
     * @param StoreRequest $request
     * @return JsonResponse
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \Throwable
     * @author luffyzhao@vip.126.com
     */
    public function store(StoreRequest $request)
    {
        return $this->response(
            DB::transaction(function () use ($request) {
                $this->book->store($request->only(['file']));
            })
        );
    }

    /**
     * @param $id
     * @return JsonResponse
     * @throws \Exception
     * @author luffyzhao@vip.126.com
     */
    public function destroy($id)
    {
        return $this->response(
            $this->book->delete($id)
        );
    }
}